$(document).ready(function() {
    if (!utils.checkAuth()) return;
    
    const userInfo = JSON.parse(localStorage.getItem(STORAGE_KEYS.USER_INFO));
    $('#userName').text(`${userInfo.name}（学生）`);
    
    // 缓存常用的DOM元素
    const $courseList = $('#courseList');
    const $evaluationListTable = $('#evaluationListTable');
    const $evaluationForm = $('#evaluationForm');
    const $courseMessage = $('#courseMessage');
    const $evaluationMessage = $('#evaluationMessage');
    const $evaluationListMessage = $('#evaluationListMessage');
    
    // 页面加载时获取数据
    loadCourses();
    loadEvaluations();
    
    // 绑定评价表单提交事件
    $evaluationForm.on('submit', function(e) {
        e.preventDefault();
        submitEvaluation();
    });
});

// 加载学生课程列表
function loadCourses() {
    $.ajax({
        url: getFullApiPath(ROLE_API_PATHS[1], '/classes'),
        type: 'GET',
        headers: utils.getAuthHeader(),
        success: function(response) {
            const result = utils.handleApiResponse(response);
            const $courseList = $('#courseList');
            $courseList.empty();
            
            if (!result.success || !result.data || !result.data.length) {
                $courseList.append('<tr><td colspan="7" class="text-center">暂无课程数据</td></tr>');
                return;
            }
            
            result.data.forEach(function(course) {
                const hasEvaluated = course.evaluated || false;
                const status = hasEvaluated ? 
                    '<span class="badge bg-success">已评价</span>' : 
                    '<span class="badge bg-warning">未评价</span>';
                
                const action = hasEvaluated ? 
                    '<button class="btn btn-sm btn-secondary" disabled>已评价</button>' :
                    `<button class="btn btn-sm btn-primary" onclick="showEvaluationModal(${course.ClassID}, '${utils.escapeHtml(course.CourseName)}', '${utils.escapeHtml(course.TeacherName)}')">评价</button>`;
                
                $courseList.append(`
                    <tr>
                        <td>${course.ClassID}</td>
                        <td>${utils.escapeHtml(course.CourseName)}</td>
                        <td>${utils.escapeHtml(course.TeacherName)}</td>
                        <td>${course.Semester}</td>
                        <td>${course.TimeLocation}</td>
                        <td>${status}</td>
                        <td>${action}</td>
                    </tr>
                `);
            });
        },
        error: function(xhr) {
            const errorMessage = utils.handleApiError(xhr, '加载课程列表失败');
            utils.showMessage($('#courseMessage'), errorMessage, 'danger');
        }
    });
}

// 加载我的评价列表
function loadEvaluations() {
    $.ajax({
        url: getFullApiPath(ROLE_API_PATHS[1], '/evaluations'),
        type: 'GET',
        headers: utils.getAuthHeader(),
        success: function(response) {
            const result = utils.handleApiResponse(response);
            const $evaluationListTable = $('#evaluationListTable');
            $evaluationListTable.empty();
            
            if (!result.success || !result.data || !result.data.length) {
                $evaluationListTable.append('<tr><td colspan="6" class="text-center">暂无评价数据</td></tr>');
                return;
            }
            
            result.data.forEach(function(evaluation) {
                const score = parseInt(evaluation.Score) || 0;
                const stars = '★'.repeat(score) + '☆'.repeat(5-score);
                
                $evaluationListTable.append(`
                    <tr>
                        <td>${evaluation.ClassID}</td>
                        <td>${utils.escapeHtml(evaluation.CourseName || '未知课程')}</td>
                        <td>${utils.escapeHtml(evaluation.TeacherName || '未知教师')}</td>
                        <td><div class="rating">${stars}</div></td>
                        <td>${utils.escapeHtml(evaluation.Comment || '')}</td>
                        <td>${utils.formatDate(evaluation.EvaluationTime)}</td>
                    </tr>
                `);
            });
        },
        error: function(xhr) {
            const errorMessage = utils.handleApiError(xhr, '加载评价列表失败');
            utils.showMessage($('#evaluationListMessage'), errorMessage, 'danger');
        }
    });
}

// 显示评价模态框
function showEvaluationModal(classId, courseName, teacherName) {
    $('#evaluationClassId').val(classId);
    $('#evaluationCourse').val(courseName);
    $('#evaluationTeacher').val(teacherName);
    $('#evaluationScore').val('5');
    $('#evaluationComment').val('');
    $('#evaluationMessage').addClass('d-none');
    
    const modal = new bootstrap.Modal(document.getElementById('evaluationModal'));
    modal.show();
}

// 提交评价
function submitEvaluation() {
    const userInfo = JSON.parse(localStorage.getItem(STORAGE_KEYS.USER_INFO));
    const classId = $('#evaluationClassId').val();
    const score = parseInt($('#evaluationScore').val());
    const comment = $('#evaluationComment').val().trim();
    
    if (!comment) {
        utils.showMessage($('#evaluationMessage'), '请填写评价内容', 'danger');
        return;
    }
    
    const $submitButton = $('#evaluationForm button[type="submit"]');
    const originalText = $submitButton.text();
    $submitButton.prop('disabled', true).text('提交中...');
    
    $.ajax({
        url: getFullApiPath(ROLE_API_PATHS[1], '/evaluate'),
        type: 'POST',
        headers: utils.getAuthHeader(),
        contentType: 'application/json',
        data: JSON.stringify({
            student_id: userInfo.id,
            class_id: parseInt(classId),
            score: score,
            comment: comment
        }),
        success: function(response) {
            $submitButton.prop('disabled', false).text(originalText);
            const result = utils.handleApiResponse(response);
            
            if (result.success) {
                utils.showMessage($('#evaluationMessage'), '评价提交成功！', 'success');
                setTimeout(() => {
                    bootstrap.Modal.getInstance(document.getElementById('evaluationModal')).hide();
                    loadCourses();
                    loadEvaluations();
                }, 1500);
            } else {
                utils.showMessage($('#evaluationMessage'), result.message || '评价提交失败', 'danger');
            }
        },
        error: function(xhr) {
            $submitButton.prop('disabled', false).text(originalText);
            const errorMessage = utils.handleApiError(xhr, '评价提交失败');
            utils.showMessage($('#evaluationMessage'), errorMessage, 'danger');
        }
    });
} 